#include "postgresql_query_result.h"

#ifdef ENABLE_POSTGRESQL

namespace utility
{
namespace database
{
    postgresql_fields_info::postgresql_fields_info(PGresult * res)
    {
        int fields_num = PQnfields(res);
        for (int i = 0; i < fields_num; i++)
        {
            _fields[PQfname(res, i)] = i;
        }
    }

    postgresql_query_result::postgresql_query_result(PGresult * res):
        _fields_info(new postgresql_fields_info(res))
    {
        res == NULL ? reserve(0) : reserve(PQntuples(res));
        int result_count = PQntuples(res);
        int fields_count = get_field_count();
        for (int i = 0; i < result_count; i++)
        {
            row::list_type values;
            for (int j = 0; j < fields_count; j++)
            {
                values.push_back(row::value_type(PQgetvalue(res, i, j), PQgetlength(res, i, j)));
            }
            push_back(row(_fields_info, values));
        }
    }

    postgresql_query_result::~postgresql_query_result(void)
    {
        delete _fields_info;
    }

    uint32 postgresql_query_result::get_field_count() const
    {
        return _fields_info->get_fields_count();
    }

    int32 postgresql_query_result::get_field_index(const char * field_name) const
    {
        return (*_fields_info)[field_name];
    }
}
}

#endif // endif of ENABLE_POSTGRESQL


